﻿using SmartForm.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace SmartlForm.Common
{
    public class XmlHelper
    {
        public static string XmlSerialize<T>(T obj)
        {
            using (StringWriter sw = new StringWriter())
            {
                Type t = obj.GetType();
                XmlSerializer serializer = new XmlSerializer(obj.GetType());
                serializer.Serialize(sw, obj);
                sw.Close();
                return sw.ToString();
            }
        }

        public static T DESerializer<T>(string strXML) where T : class
        {
            try
            {
                using (StringReader sr = new StringReader(strXML))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(T));
                    return serializer.Deserialize(sr) as T;
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }


        public static T DESerializerByPath<T>(string path) where T : class
        {
            try
            {
                string strXML = Read(path);
                using (StringReader sr = new StringReader(strXML))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(T));
                    return serializer.Deserialize(sr) as T;
                }
            }
            catch (Exception ex)
            {
                Console.Write(ex.ToString());
                LogUtil.WriteLog("DESerializerByPath", ex);
                return null;
            }
        }

        // 读操作
        public static string Read(string path)
        {
            // 读取文件的源路径及其读取流
            string strReadFilePath = path;
            StreamReader srReadFile = new StreamReader(strReadFilePath);

            string strReadLine = string.Empty;
            // 读取流直至文件末尾结束
            while (!srReadFile.EndOfStream)
            {
                strReadLine += srReadFile.ReadLine() + "\r\n"; //读取每行数据
            }
            // 关闭读取流文件
            srReadFile.Close();
            return strReadLine;
        }



    }
}
